package virtorina.client.room;

import virtorina.client.room.dto.InfoDTO;
import virtorina.client.room.dto.QuestionDTO;
import virtorina.client.room.rpc.GWTService4Room;
import virtorina.client.room.rpc.GWTService4RoomAsync;

import com.google.gwt.core.client.GWT;
import com.google.gwt.maps.client.InfoWindowContent;
import com.google.gwt.maps.client.MapType;
import com.google.gwt.maps.client.MapWidget;
import com.google.gwt.maps.client.control.Control;
import com.google.gwt.maps.client.control.LargeMapControl;
import com.google.gwt.maps.client.event.MapClickHandler;
import com.google.gwt.maps.client.event.MapMouseOverHandler;
import com.google.gwt.maps.client.event.MapClickHandler.MapClickEvent;
import com.google.gwt.maps.client.event.MapMouseOverHandler.MapMouseOverEvent;
import com.google.gwt.maps.client.geom.LatLng;
import com.google.gwt.maps.client.overlay.Marker;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

public class Main {
	private long LastTime;
	private Label time;
	private VerticalPanel question;
	private HTML questTop;
	private long duration;
	private Integer ROOM_ID;
	Virtorina virt;

	// ProgessBar pb;
	public Main(int id, Virtorina main) {
		this.virt = main;
		ROOM_ID = id;
		exportStaticMethod();
		time = new Label("..");
		questTop = new HTML();
		RootPanel.get("question").add(questTop);
		RootPanel.get("persent").add(time);
		RootPanel.get("timeBar").setWidth("0%");
		LastTime = 0;
		Window.setTitle("IQ: " + virt.name + " room");

	}

	public static native void exportStaticMethod() /*-{
													$wnd.compsend = $entry(@virtorina.client.room.Main::compsend(I));
													}-*/;

	public static native void compsend(int i) /*-{
												@virtorina.client.room.Main::JavaCompSend(I)(i);
												}-*/;

	public void start() {
		new Timer() {
			@Override
			public void run() {
				LastTime -= 50;
				if (LastTime > 0) {
					// pb.setProgress((double)(30-LastTime/1000)/30);
					time.setText(LastTime / 1000 + "");
					double persent = LastTime;
					persent = 100 - persent / duration * 100;
					if (persent > 70) {
						RootPanel.get("timeline").removeStyleName(
								"progress-info");
						RootPanel.get("timeline").addStyleName(
								"progress-danger");
					}
					if (persent >= 100) {
						RootPanel.get("timeline").setWidth("0%");
					}
					RootPanel.get("timeBar").setWidth(persent + "%");
					Window.setTitle("[" + LastTime / 1000 + "] IQ:" + virt.name
							+ " room");
				} else {
					RootPanel.get("timeline").setWidth("0%");
					time.setText("...");
					Window.setTitle("IQ: " + virt.name + " room");
				}
			}
		}.scheduleRepeating(50);
	}

	public void setMyltiInfo(InfoDTO result) {
		StringBuilder sb = new StringBuilder();
		VerticalPanel right = new VerticalPanel();
		VerticalPanel left = new VerticalPanel();
		right.setWidth("200px");

		String question = result.getQuestion();
		String stuff = "";
		if (result.getType() == 1) {
			question = result.getQuestion().substring(0,
					result.getQuestion().indexOf("@$PE"));
			stuff = result.getQuestion().substring(
					result.getQuestion().indexOf("@$PE") + 4);
		}
		for (String s : question.split(" ")) {
			sb.append(s + "<wbr> ");
		}
		left.add(new HTML("<b>Question:</b> " + sb.toString() + ""));
		if (result.getType() == 1) {
			left.add(new HTML(
					"<img style=\"display: block; max-width:200px; max-height: 400px;\" src=\""
							+ stuff + "\">"));
		} else if (result.getType() == 3) {
			LatLng center = LatLng.newInstance(0D, 0D);
			final MapWidget map = new MapWidget(center, 1);
			for (String s : result.getAnswers()) {
				LatLng mcord = LatLng.newInstance(
						new Double(s.substring(0, s.indexOf(','))), new Double(
								s.substring(s.indexOf(',') + 1)));
				map.addOverlay(new Marker(mcord));
				map.setCenter(mcord);
			}
			map.setSize("200px", "200px");
			left.add(map);
		}
		sb = new StringBuilder();
		sb.append("<b>Answers:</b> ");
		boolean f = false;
		for (String s : result.getAnswers()) {
			if (f) {
				sb.append(", ");
			}
			f = true;
			sb.append(s);
		}
		sb.append("<br>");
		if (result.getWinners().isEmpty()) {
			sb.append("No one answered correctly<br>");
		} else {
			sb.append("<b>Answered correctly:</b><br>");
			for (String nick : result.getWinners()) {
				sb.append("<b style=\"color: green;\">" + nick + "</b><br>");
			}
		}
		sb.append("<b>Subjects:</b> ");
		for (String t : result.getLabels()) {
			sb.append("<span class=\"label\">" + t + "</span> ");
		}
		sb.append("<br>");
		sb.append("<b>Iterations:</b> " + result.getIterations() + "<br>");
		if (!result.getChecked()) {
			sb.append("Not approved by moderator<br>");
		}
		sb.append("<b>Rating:</b> " + result.getRank() + " ("
				+ result.getNumOfRank() + ")<br>");
		sb.append("<b>Provider:</b> " + result.getProvider() + "<br>");
		sb.append("</b>Rate the question:</b><br>"
				+ "<span style=\"position: absolute; left: 60%;\"><div class=\"btn-group\"><a onClick='compsend(-1)' rel=\"tooltip\" title=\"Like\" class=\"btn btn-success\" href=\"#\">"
				+ "<i style=\"color: white;\" class=\"icon-thumbs-up\"></i></a>"
				+ "<a rel=\"tooltip\" title=\"Dislike\" class=\"btn btn-danger dropdown-toggle\" data-toggle=\"dropdown\""
				+ ";>&nbsp<i style=\"color: white;\" class=\"icon-thumbs-down\"></i>&nbsp</a>"
				+ "<ul class=\"dropdown-menu\">"
				+ "<li><a onClick='compsend(0);'>Boring</a></li>"
				+ "<li><a onClick='compsend(1);'>Ambiguous</a></li>"
				+ "<li><a onClick='compsend(2);'>Violative</a></li>"
				+ "<li><a onClick='compsend(3);'>Incorrect</a></li>"
				+ "<li><a onClick='compsend(4);'>Lacking subjects</a></li>"
				+ "</ul></div></span>");
		right.add(new HTML(sb.toString()));
		right.addStyleName("tableCenter");
		HorizontalPanel hp = new HorizontalPanel();
		hp.add(left);
		hp.add(right);
		hp.setSpacing(100);
		RootPanel.get("info").add(hp);
	}

	public void getInfo() {
		((GWTService4RoomAsync) GWT.create(GWTService4Room.class)).getInfo(
				ROOM_ID, new AsyncCallback<InfoDTO>() {

					@Override
					public void onSuccess(InfoDTO result) {
						RootPanel.get("question").clear();
						RootPanel.get("question").setVisible(false);
						RootPanel.get("info").setVisible(true);
						RootPanel.get("timeline").setWidth("0%");
						LastTime = result.getNextTime();
						duration = result.getDuration();
						RootPanel.get("timeline").removeStyleName(
								"progress-danger");
						RootPanel.get("timeline").addStyleName("progress-info");
						setMyltiInfo(result);

					}

					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub

					}
				});
	}

	private void setTextAndImageQuestion(QuestionDTO result) {
		StringBuilder sb = new StringBuilder();
		for (Character c : result.getQuestion().toCharArray()) {
			sb.append(c + " - " + (int) c + "<br>");
		}
		String stuff = "";
		String question = result.getQuestion();
		if (result.getType() > 0) {
			question = result.getQuestion().substring(0,
					result.getQuestion().indexOf("@$PE"));
			stuff = result.getQuestion().substring(
					result.getQuestion().indexOf("@$PE") + 4);
		}
		StringBuilder questRes = new StringBuilder();
		for (String q : question.split(" ")) {
			questRes.append(q + "<wbr> ");
		}
		StringBuilder res = new StringBuilder(
				"<h1 style=\"padding-top:20px;\">" + question + "</h1>");
		if (result.getType() == 1) {
			res.append("<img style=\"display: block; max-width:400px; maix-width:600px;  margin-left: auto;   margin-right: auto;\" src=\""
					+ stuff + "\">");
		}
		RootPanel.get("question").clear();
		RootPanel.get("question").add(new HTML(res.toString()));
	}

	private void setMapQuestion(QuestionDTO result) {
		LatLng center = LatLng.newInstance(0D, 0D); // центр карты
		final MapWidget map = new MapWidget(center, 1);
		map.setDoubleClickZoom(false);
		map.setDraggable(false);
		map.addMapClickHandler(new MapClickHandler() {

			@Override
			public void onClick(MapClickEvent event) {
				LatLng laln = event.getLatLng();

				String lat = (laln.getLatitude() + "");
				if (lat.length() > 6) {
					lat = lat.substring(0, 6);
				}
				String lon = (laln.getLongitude() + "");
				if (lon.length() > 6) {
					lon = lon.substring(0, 6);
				}
				String pos = lat + "," + lon;
				virt.chat.pushAnswer(pos);
			}
		});
		map.setSize("640px", "400px");
		RootPanel.get("question").clear();
		RootPanel.get("question").add(
				new HTML("<h1 style=\"padding-top:20px;\">"
						+ result.getQuestion() + "</h1>"));
		RootPanel.get("question").add(map);
	}

	public void getQuestion() {
		((GWTService4RoomAsync) GWT.create(GWTService4Room.class)).getQuestion(
				ROOM_ID, new AsyncCallback<QuestionDTO>() {

					@Override
					public void onSuccess(QuestionDTO result) {
						RootPanel.get("timeline").setWidth("0%");
						RootPanel.get("timeline").removeStyleName(
								"progress-danger");
						RootPanel.get("timeline").addStyleName("progress-info");
						LastTime = result.getQtime();
						duration = result.getDuration();
						RootPanel.get("info").clear();
						RootPanel.get("info").setVisible(false);
						RootPanel.get("question").setVisible(true);
						if (result.getType() == 0 || result.getType() == 1) {
							setTextAndImageQuestion(result);
						} else if (result.getType() == 3) {
							setMapQuestion(result);
						}
					}

					@Override
					public void onFailure(Throwable caught) {

					}
				});
	}

	private static void JavaCompSend(int i) {
		((GWTService4RoomAsync) GWT.create(GWTService4Room.class))
				.setComplaint(
						new Integer(com.google.gwt.user.client.Window.Location
								.getParameter("id")), i,
						new AsyncCallback<Integer>() {

							@Override
							public void onSuccess(Integer result) {

							}

							@Override
							public void onFailure(Throwable caught) {
								// TODO Auto-generated method stub

							}
						});
	}
}